/**
 * Project Name : pgw-core
 * File Name : BeanUtils.java
 * Package Name : com.i2f.ect.pgw.util
 * Date : 2015年6月2日上午10:33:13
 * Copyright (c) 2015, i2Finance Software All Rights Reserved
 */
package com.ess.utils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ess.constants.Constants;

/**
 * ClassName : Bean工具类 <br/>
 * Date : 2016年6月29日 上午10:33:13 <br/>
 *
 * @author tanlq
 * @version
 * @since JDK 1.7
 * @see
 */
public final class BeanUtils {
    public static final String METHOD_GET = "get";
    public static final String METHOD_SET = "set";
    public static final String EXCLUDE_FILED_NAME = "serialVersionUID";

    private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 对象转为map
     * @param object
     * @return
     */
    public static Map<String, Object> beanToMap(Object object) {
        if (null == object) {
            return null;
        }
        Map<String, Object> beanMap = new HashMap<String, Object>();
        Class<?> clazz = object.getClass();
        while (null != clazz) {
            clazz = wrapFieldToMap(clazz, object, beanMap);
        }
        return beanMap;
    }

    /**
     *
     * @param clazz
     * @param object
     * @param beanMap
     * @return
     */
    private static Class<?> wrapFieldToMap(Class<?> clazz, Object object, Map<String, Object> beanMap) {
        Field[] fields = clazz.getDeclaredFields();
        if (null == fields) {
            return clazz.getSuperclass();
        }
        for (Field field : fields) {
            String fieldName = field.getName();
            if (EXCLUDE_FILED_NAME.equals(fieldName)) {
                continue;
            }
            Object obj = getFieldValueByName(clazz, object, fieldName);
            beanMap.put(fieldName, obj);
        }
        return clazz.getSuperclass();
    }

    public static Object getFieldValueByName(Class<?> clazz, Object obj, String fieldName) {
        if (null == clazz || null == obj || null == fieldName) {
            return null;
        }
        String methodName = null;
        if (fieldName.length() == 1) {
            methodName = METHOD_GET + fieldName.toUpperCase();
        } else {
            methodName = METHOD_GET + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        }
        try {
            return clazz.getMethod(methodName).invoke(obj);
        } catch (Exception e) {
            return null;
        }
    }

    public static void convertEmptyStringToNull(Object obj) throws IllegalArgumentException, IllegalAccessException {
        Field[] fs = obj.getClass().getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); //设置属性是可以访问的
            Object val = f.get(obj);//得到此属性的值
            String type = f.getType().toString();//得到此属性的类型
            if (type.endsWith("String")) {
                if (null != val && ("".equals(val.toString()) || "NULL".equals(val.toString().toUpperCase()))) {
                    f.set(obj, null); //将空字符串或设置为空对象
                }
            }
        }
    }

    /**
     * 设置默认字段  包括 删除，创建时间，更新时间，更新者等字段
     *
     */
    public static void setDefaultField(Object obj, String flag) throws Exception {
        Field[] fs = obj.getClass().getDeclaredFields();
        String createUser = "";
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            f.setAccessible(true); //设置属性是可以访问的
            String name = f.getName();
            //新增时候需要的默认字段  创建时间，删除
            if (Constants.FLAG_SAVE.equals(flag)) {
                if ("createDate".equalsIgnoreCase(name)) {
                    f.set(obj, new Date());
                }
                if ("createUser".equalsIgnoreCase(name)) {
                    createUser = f.get(obj).toString();
                }
                if ("updateUser".equalsIgnoreCase(name)) {
                    f.set(obj, createUser);
                }
            }
            if ("updateDate".equalsIgnoreCase(name)) {
                f.set(obj, new Date());
            }
        }
    }


    /**
     * 更新操作 包括上面两个方法   去掉空字符串，设置更新参数
     *
     */
    public static void proviousOperate(Object obj, String flag) throws Exception {
        convertEmptyStringToNull(obj);
        setDefaultField(obj,flag);
    }

}
